<template>
  <el-dialog
    v-model="visible"
    :title="title"
    width="500px"
    @close="handleClose"
  >
    <div class="person-selector">
      <!-- 选择方式切换 -->
      <el-radio-group v-model="selectMode" class="mode-selector">
        <el-radio-button label="dropdown">下拉选择</el-radio-button>
        <el-radio-button label="tree">树形选择</el-radio-button>
      </el-radio-group>

      <!-- 下拉选择模式 -->
      <div v-if="selectMode === 'dropdown'" class="dropdown-mode">
        <el-select
          v-model="selectedPersons"
          multiple
          filterable
          placeholder="请选择人员"
          style="width: 100%"
          @change="handleSelectionChange"
        >
          <el-option
            v-for="person in allPersons"
            :key="person.id"
            :label="person.name"
            :value="person.id"
          >
            <span style="float: left">{{ person.name }}</span>
            <span style="float: right; color: #8492a6; font-size: 13px">{{ person.department }}</span>
          </el-option>
        </el-select>
      </div>

      <!-- 树形选择模式 -->
      <div v-if="selectMode === 'tree'" class="tree-mode">
        <el-tree
          ref="treeRef"
          :data="treeData"
          :props="treeProps"
          show-checkbox
          node-key="id"
          :default-checked-keys="selectedPersonIds"
          @check="handleTreeCheck"
        >
          <template #default="{ data }">
            <span class="tree-node">
              <el-icon v-if="data.type === 'department'"><OfficeBuilding /></el-icon>
              <el-icon v-else><User /></el-icon>
              <span>{{ data.name }}</span>
            </span>
          </template>
        </el-tree>
      </div>

      <!-- 已选择的人员列表 -->
      <div v-if="selectedPersons.length > 0" class="selected-persons">
        <h4>已选择的人员：</h4>
        <el-tag
          v-for="person in selectedPersons"
          :key="person.id"
          closable
          @close="removePerson(person.id)"
          class="person-tag"
        >
          {{ person.name }}
        </el-tag>
      </div>
    </div>

    <template #footer>
      <span class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" @click="handleConfirm">确定</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, computed, watch } from 'vue'
import { ElDialog, ElRadioGroup, ElRadioButton, ElSelect, ElOption, ElTree, ElTag, ElButton, ElIcon } from 'element-plus'
import { OfficeBuilding, User } from '@element-plus/icons-vue'

// Props
const props = defineProps<{
  modelValue: boolean
  title: string
  selectedPersonIds?: string[]
}>()

// Emits
const emit = defineEmits<{
  'update:modelValue': [value: boolean]
  'confirm': [personIds: string[], persons: any[]]
}>()

// 响应式数据
const visible = computed({
  get: () => props.modelValue,
  set: (value) => emit('update:modelValue', value)
})

const selectMode = ref('dropdown')
const selectedPersons = ref<any[]>([])
const selectedPersonIds = ref<string[]>(props.selectedPersonIds || [])
const treeRef = ref()

// 模拟人员数据
const allPersons = ref([
  { id: '1', name: '张三', department: '技术部', position: '高级工程师' },
  { id: '2', name: '李四', department: '技术部', position: '工程师' },
  { id: '3', name: '王五', department: '产品部', position: '产品经理' },
  { id: '4', name: '赵六', department: '产品部', position: '产品专员' },
  { id: '5', name: '钱七', department: '运营部', position: '运营经理' },
  { id: '6', name: '孙八', department: '运营部', position: '运营专员' },
  { id: '7', name: '周九', department: '人事部', position: '人事经理' },
  { id: '8', name: '吴十', department: '人事部', position: '人事专员' },
  { id: '9', name: '郑十一', department: '财务部', position: '财务经理' },
  { id: '10', name: '王十二', department: '财务部', position: '会计' }
])

// 树形数据
const treeData = computed(() => {
  const departments = ['技术部', '产品部', '运营部', '人事部', '财务部']
  return departments.map(dept => ({
    id: `dept-${dept}`,
    name: dept,
    type: 'department',
    children: allPersons.value
      .filter(person => person.department === dept)
      .map(person => ({
        id: person.id,
        name: person.name,
        type: 'person',
        department: person.department,
        position: person.position
      }))
  }))
})

// 树形选择配置
const treeProps = {
  children: 'children',
  label: 'name'
}

// 监听选中人员ID变化
watch(selectedPersonIds, (newIds) => {
  selectedPersons.value = allPersons.value.filter(person => newIds.includes(person.id))
}, { immediate: true })

// 下拉选择变化
const handleSelectionChange = (personIds: string[]) => {
  selectedPersonIds.value = personIds
}

// 树形选择变化
const handleTreeCheck = (_data: any, checked: any) => {
  const checkedKeys = checked.checkedKeys
  const personKeys = checkedKeys.filter((key: string) => !key.startsWith('dept-'))
  selectedPersonIds.value = personKeys
}

// 移除人员
const removePerson = (personId: string) => {
  selectedPersonIds.value = selectedPersonIds.value.filter(id => id !== personId)
}

// 关闭弹窗
const handleClose = () => {
  visible.value = false
}

// 确认选择
const handleConfirm = () => {
  emit('confirm', selectedPersonIds.value, selectedPersons.value)
  handleClose()
}
</script>

<style scoped>
.person-selector {
  padding: 20px 0;
}

.mode-selector {
  margin-bottom: 20px;
  display: flex;
  justify-content: center;
}

.dropdown-mode,
.tree-mode {
  margin-bottom: 20px;
}

.tree-mode {
  max-height: 300px;
  overflow-y: auto;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  padding: 10px;
}

.tree-node {
  display: flex;
  align-items: center;
  gap: 8px;
}

.selected-persons {
  margin-top: 20px;
  padding-top: 20px;
  border-top: 1px solid #ebeef5;
}

.selected-persons h4 {
  margin: 0 0 10px 0;
  color: #606266;
  font-size: 14px;
}

.person-tag {
  margin-right: 8px;
  margin-bottom: 8px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
</style>
